package com.kayt.cyberBar.company.business.server.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kayt.cyberBar.common.cache.PublicCache;
import com.kayt.cyberBar.company.business.dao.ICompanyBaseUnitMapDao;
import com.kayt.cyberBar.company.business.entity.po.BCompanyBaseUnitMap;
import com.kayt.cyberBar.company.business.entity.vo.CompanyBaseUnitMapVO;
import com.kayt.cyberBar.company.business.server.ICompanyBaseUnitMapServer;
import com.kayt.cyberBar.cpublic.business.entity.vo.PublicUnitCountVO;
import com.kayt.cyberBar.log.business.server.impl.LogOperateImpl;

@Service("iCompanyBaseUnitMapServer")
public class CompanyBaseUnitMapServerImpl extends LogOperateImpl implements ICompanyBaseUnitMapServer {
	private static Logger logger = LoggerFactory.getLogger(CompanyBaseUnitMapServerImpl.class);

	@Autowired
	private PublicCache publicCache;
	
	@Autowired
	private ICompanyBaseUnitMapDao iCompanyBaseUnitMapDao;
	
	@Override
	public BCompanyBaseUnitMap get_map_by_itemcode (String itemCode) {
		if (StringUtils.isNotBlank(itemCode)) {
			try {
				return this.iCompanyBaseUnitMapDao.getUnitMapByCode(itemCode);
			} catch (SQLException e) {
				logger.error("get_map_by_maincode with a SQLException", e);
			}
		}
		return null;
	}

	@Override
	public CompanyBaseUnitMapVO assemble_vo (BCompanyBaseUnitMap unitMap) {
		if (unitMap != null) {
			CompanyBaseUnitMapVO rspVO = new CompanyBaseUnitMapVO();
			rspVO.setCode(unitMap.getCode());
			String id = unitMap.getId() == null ? null : unitMap.getId().toString();
			rspVO.setId(id);
			rspVO.setItemCode(unitMap.getItemCode());
			rspVO.setItemName(unitMap.getItemName());
			rspVO.setCreateTime(unitMap.getCreateTime());
			rspVO.setElementCount(unitMap.getElementCount());
			rspVO.setElementUnitCountCode(unitMap.getElementUnitCountCode());
			rspVO.setParentUnitCountCode(unitMap.getParentUnitCountCode());
			rspVO.setParentCount(unitMap.getParentCount());
			rspVO.setStatusCode(unitMap.getStatusCode());
			rspVO.setUpdateTime(unitMap.getUpdateTime());
			
			List<PublicUnitCountVO> countList = this.publicCache.getUnitCountList();
			if (countList != null && countList.size() > 0) {
				for (PublicUnitCountVO item : countList) {
					if (item != null) {
						if (item.getCode() != null && item.getCode().equals(unitMap.getParentUnitCountCode())) {
							rspVO.setParentUnitCount(item.getUnitCount());
						}
						if (item.getCode() != null && item.getCode().equals(unitMap.getElementUnitCountCode())) {
							rspVO.setElementUnitCount(item.getUnitCount());
						}
					}
				}
			}
			return rspVO;
		}
		return null;
	}
}
